﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace MetaDemo.Forms
{
    public partial class LoadAssemblyForm : Form
    {
        public static Form Get()
        {
            return new LoadAssemblyForm();
        }



        public LoadAssemblyForm()
        {
            InitializeComponent();

            this.DragEnter += new DragEventHandler(LoadAssemblyForm_DragEnter);
            this.DragDrop += new DragEventHandler(LoadAssemblyForm_DragDrop);
            lblInvitation.DragEnter += new DragEventHandler(LoadAssemblyForm_DragEnter);
            lblInvitation.DragDrop += new DragEventHandler(LoadAssemblyForm_DragDrop);

            // Close form when ESC is pressed.
            this.KeyDown += new KeyEventHandler(LoadAssemblyForm_KeyDown);
        }



        
        #region event handler

        void LoadAssemblyForm_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.All;
        }



        void LoadAssemblyForm_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                Array a = (Array)e.Data.GetData(DataFormats.FileDrop);

                if (a == null)
                {
                    Console.WriteLine("ERROR: Cannot accept the drop data.");
                    return;
                }

                // We expect precisely one file: ending with dll.
                if (1 != a.Length) {
                    Console.WriteLine("ERROR: Will only accept single files.");
                    return;
                }

                string s = a.GetValue(0).ToString();

                if (!s.EndsWith(".dll") && !s.EndsWith(".exe")) {
                    Console.WriteLine("ERROR: Expecting file to end with .exe or .dll.");
                    return;
                }

                this.Activate();        // in the case Explorer overlaps this form

                // Try to load assembly.
                Assembly.LoadFrom(s);
                Console.WriteLine("Successfully loaded: " + s);
                Console.WriteLine("Now loaded: ");
                foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
                {
                    Console.WriteLine(" - " + assembly.FullName);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("Error in DragDrop function: " + ex.Message);

                // don't show MessageBox here - Explorer is waiting !

            }
        }

        void LoadAssemblyForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
                this.Dispose();
        }

        
        #endregion
    }
}
